<template>
  <div class="product-list">
    <div class="toolbar">
      <el-input
        v-model="search.title"
        style="width: 240px"
        placeholder="请输入商品名"
        clearable
        :prefix-icon="Search"
        @change="onSearchChange"
      />
    </div>

    <div class="btn-group">
      <el-button-group>
        <el-button type="primary" :icon="Plus" @click="plusRow">添加</el-button>
        <el-button type="danger" :icon="Delete" @click="deleteAll"
          >删除全部</el-button
        >
      </el-button-group>
    </div>

    <el-table
      ref="tableRef"
      :data="tableData"
      @sort-change="sortChange"
      tooltip-effect="light"
      :show-overflow-tooltip="true"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55px" />
      <!-- <el-table-column prop="id" label="ID" sortable width="100ox" /> -->
      <el-table-column
        sortable
        fixed
        label="创建日期"
        width="150px"
        prop="createTime"
      >
        <template #default="{ row }">
          {{ getFormatTime(row.createTime, true) }}
        </template>
      </el-table-column>
      <el-table-column
        sortable
        fixed
        label="更新日期"
        width="150px"
        prop="updateTime"
      >
        <template #default="{ row }">
          {{ getFormatTime(row.updateTime, true) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="classificationSecondName"
        label="分类名称"
        fixed
        width="100ox"
      />
      <el-table-column prop="repertory" label="库存" sortable width="100ox" />
      <el-table-column prop="price" label="价格" sortable width="100ox" />
      <el-table-column
        prop="collectCount"
        label="收藏数"
        sortable
        width="100ox"
      />
      <el-table-column prop="wishCount" label="点赞数" sortable width="100ox" />
      <el-table-column prop="pv" label="PV" sortable width="100ox" />
      <el-table-column
        prop="recommendCount"
        label="推荐数"
        sortable
        width="100ox"
      />

      <el-table-column prop="status" label="状态" sortable width="100ox">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @click="switchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="description" label="简介" sortable width="100ox" />
      <el-table-column
        prop="title"
        fixed
        label="商品名"
        sortable
        width="100ox"
      />

      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            :icon="Edit"
            circle
            size="small"
            @click="editRow(scope)"
          >
          </el-button>
          <el-button
            link
            type="danger"
            :icon="Delete"
            circle
            size="small"
            @click="deleteRow(scope)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        :page-sizes="[2, 5, 20, 40, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :default-page-size="pagination.size"
        @change="onPaginationChange"
      />
    </div>

    <el-dialog
      class="updateDialog"
      v-model="plusAndEditDialog.isVisible"
      :title="plusAndEditDialog.title"
      align-center
    >
      <el-form label-width="100px" label-position="left">
        <el-form-item label="商品名">
          <el-input v-model="plusAndEditForm.title" />
        </el-form-item>
        <el-form-item label="封面">
          <el-input v-model="plusAndEditForm.cover" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="plusAndEditForm.price" />
        </el-form-item>
        <el-form-item label="二级标签">
          <el-select
            v-model="optionValue"
            placeholder="请选择二级标签"
            size="large"
            style="height: 30px"
          >
            <el-option
              v-for="item in classificationSecondOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="库存量">
          <el-input v-model="plusAndEditForm.repertory" />
        </el-form-item>
        <el-form-item label="状态">
          <span>下架&nbsp;</span>
          <el-switch
            v-model="plusAndEditForm.status"
            active-value="1"
            inactive-value="0"
          />
          <span>&nbsp;上市</span>
        </el-form-item>
        <el-form-item label="商品热度">
          <el-input v-model="plusAndEditForm.score" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input
            v-model="plusAndEditForm.description"
            style="width: 240px"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="Please input"
          />
          <!-- <el-input v-model="plusAndEditForm.description" /> -->
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button @click="centerDialogVisible = false">Cancel</el-button> -->
          <el-button type="primary" @click="save"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  thingPage,
  thingDeleteByUserId,
  thingDeleteBatch,
  thingAdd,
  thingEdit,
} from "@/apis/thing";
import { Delete, Edit, Plus, Search } from "@element-plus/icons-vue";
import { reactive, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getFormatTime } from "@/apis/utility";
import { classificationSecondPage } from "@/apis/admin/classificationSecond";
const router = useRouter();

const products = ref([]);
// 存储表格数据的变量
const tableData = ref([]);
// 搜索输入框搜索条件
const search = reactive({
  title: "",
});

/**
 * 搜索输入框对应的触发事件
 * @param {String} value 输入框值
 */

const onSearchChange = () => {
  getPage();
};

// 存储排序字段
const orders = reactive({
  column: "id",
  isAsc: true,
});
/**
 * 表格排序函数
 * @param {*} column 当前列对
 * @param {*} prop 当前字段
 * @param {*} order 当前排序方式
 */
const sortChange = ({ prop, order }) => {
  console.log(prop, order);

  Object.assign(orders, {
    column: `CAST(${prop} AS UNSIGNED)`,
    isAsc: order === "ascending",
  });
  getPage();
};

/**
 * 删除一行
 * @param {*} scope
 */
const deleteRow = (scope) => {
  console.log(scope);
  thingDeleteByUserId(scope.row.id).then((result) => {
    console.log(result);
    getPage();
  });
};

/**
 * 获取表格组件引用对象： 前提在表格上加上 ref="tableRef"

 */
const tableRef = ref();
/**
 * 删除全部选中行
 */
const deleteAll = async () => {
  const selectionRows = tableRef.value.getSelectionRows();
  // console.log(selectionRows);
  const ids = await selectionRows.map((row) => {
    return row.id;
  });

  await thingDeleteBatch(ids);
  getPage();
  // console.log(ids)
};

/**
 * 分页查询
 * @param {*} filter 过滤
 * @param {*} search 搜索
 * @param {*} orders 排序
 */
const getPage = async () => {
  const result = await thingPage(
    {
      search: search,
      orders: [orders],
    },
    pagination.page,
    pagination.size
  );

  if (result != undefined) {
    tableData.value = result.data.records;
    pagination.total = result.data.total;
  }
};

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});
/**
 * 分页改变函数
 * @param {*} currentPage 当前页
 * @param {*} pageSize 每页条数
 */

const onPaginationChange = (currentPage, pageSize) => {
  pagination.page = currentPage;
  pagination.size = pageSize;
  getPage();
};

/**
 * 添加和修改表格数据
 */
const plusAndEditForm = ref({});

/**
 * 添加和修改的对话框
 */
const plusAndEditDialog = reactive({
  isVisible: false,
  title: "",
});

/**
 * 修改当前行的数据
 * @param {*} scope
 */

const editRow = (scope) => {
  plusAndEditDialog.isVisible = true;
  plusAndEditDialog.title = "修改";
  plusAndEditForm.value = {};
  optionValue.value = "";
  // console.log(scope);
  Object.assign(plusAndEditForm.value, scope.row);
  // console.log(plusAndEditForm)
  getClassificationSecondOptionsPage();
  // console.log(optionValue.value);
};

/**
 * 添加一行数据
 */
const plusRow = () => {
  plusAndEditDialog.isVisible = true;
  plusAndEditDialog.title = "添加";
  plusAndEditForm.value = {};
  optionValue.value = "";
  getClassificationSecondOptionsPage();
  // console.log(optionValue.value);
};
/**
 * 修改和添加的保存功能
 */
const save = async () => {
  plusAndEditDialog.isVisible = false;
  // console.log(plusAndEditForm.value);

  if (plusAndEditDialog.title == "添加") {
    plusAndEditForm.value.classificationSecondId = optionValue.value;
    console.log(plusAndEditForm.value);
    await thingAdd(plusAndEditForm.value).then(() => {});
    getPage();
  } else if (plusAndEditDialog.title == "修改" && plusAndEditForm.value.id) {
    plusAndEditForm.value.classificationSecondId = optionValue.value;
    thingEdit(plusAndEditForm.value).then(() => {
      console.log(plusAndEditForm);
      getPage();
    });
  }
  // console.log(optionValue.value);
  // console.log(plusAndEditForm.value);
};

// 生命周期
onMounted(() => {
  // 页面加载的时候立刻执行一次请求
  getPage();
});

// 多选框默认值
const optionValue = ref("");
// 多选框取值
const classificationSecondOptions = ref([]);

// 获取二级标签

const classificationSecondPagination = reactive({
  page: 1,
  size: 100,
});
const getClassificationSecondOptionsPage = async () => {
  try {
    const result = await classificationSecondPage(
      {},
      classificationSecondPagination.page,
      classificationSecondPagination.size
    );
    classificationSecondOptions.value = result.data.records;
    // console.log( classificationSecondOptions.value );
    // console.log(optionValue.value);
  } catch (error) {
    console.error(error);
  }
};
</script>

<style scoped lang="less">
.toolbar {
  padding-bottom: 10px;
  display: flex;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.el-table {
  height: calc(100vh - 225px);
}

.filter {
  display: flex;
  margin-bottom: 10px;
}
.el-input,
.el-select {
  max-width: 250px;
}
.el-form {
  padding: 20px 40px;
}
</style>
